﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;
using System.Web;

namespace BugClient
{
    public partial class ResolveForm : Form
    {
        WebClient web;
        string url;
        string token;
        string bugID;
        List<string> userList = new List<string>();

        public ResolveForm(WebClient web, string url, string token, string bugID, string openedBy, string[] users, Dictionary<string, string> userDict, string[] stateNames)
        {
            InitializeComponent();

            Text = "解决-" + bugID;
            this.web = web;
            this.url = url;
            this.token = token;
            this.bugID = bugID;
            userList.AddRange(users);
            foreach (var user in userList)
            {
                assignBox.Items.Add(userDict[user]);
            }
            assignBox.SelectedIndex = userList.IndexOf(openedBy);
            for(int i = 2; i < stateNames.Length; ++i)
            {
                resolutionBox.Items.Add(stateNames[i]);
            }
            resolutionBox.SelectedIndex = 0;
        }

        private async void commitButton_Click(object sender, EventArgs e)
        {
            if (web.IsBusy)
                return;
            string response;
            try
            {
                response = await web.UploadStringTaskAsync(url + "/resolve", string.Format("bug={0}&type={1}&assign={2}&comment={3}&token={4}", bugID, resolutionBox.SelectedIndex + 2, userList[assignBox.SelectedIndex], HttpUtility.UrlEncode(commentBox.Text), token));
            }
            catch (WebException ex)
            {
                MessageBox.Show("连接服务器失败：" + ex.Message);
                return;
            }
            if (string.IsNullOrEmpty(response))
            {
                MessageBox.Show("解决失败");
                return;
            }
            DialogResult = DialogResult.OK;
            Dispose();
            Close();
        }
    }
}
